<template>
	<div class="tabs-box">
		<div class="tabs-menu">
			<el-tabs v-model="tabsMenuValue" type="card" @tab-click="tabClick" @tab-remove="tabRemove">
				<el-tab-pane v-for="item in tabsMenuList" :key="item.path" :label="item.title" :name="item.path" :closable="item.close">
					<template #label>
						<el-icon class="tabs-icon" v-if="item.icon && themeConfig.tabsIcon">
							<component :is="item.icon"></component>
						</el-icon>
						{{ item.title }}
					</template>
				</el-tab-pane>
			</el-tabs>
			<MoreButton />
		</div>
	</div>
</template>

<script setup lang="ts">
import { ref, computed, watch, inject } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { GlobalStore } from '@/stores';
import { TabsStore } from '@/stores/modules/tabs';
import { AuthStore } from '@/stores/modules/auth';
import { TabsPaneContext } from 'element-plus';
import MoreButton from './components/MoreButton.vue';

const route = useRoute();
const router = useRouter();
const tabStore = TabsStore();
const authStore = AuthStore();
const globalStore = GlobalStore();

const tabsMenuValue = ref(route.fullPath);
const tabsMenuList = computed(() => tabStore.tabsMenuList);

const themeConfig = computed(() => globalStore.themeConfig);

// 监听路由的变化（防止浏览器后退/前进不变化 tabsMenuValue）
watch(
	() => route.fullPath,
	() => {
		// 二级详情页面不在tab中展示
		if (route.fullPath.indexOf('Info') !== -1) {
			return;
		}
		tabsMenuValue.value = route.fullPath;
		const tabsParams = {
			icon: route.meta.icon as string,
			title: route.meta.title as string,
			path: route.fullPath,
			close: !route.meta.isAffix
		};
		tabStore.addTabs(tabsParams);
	},
	{
		immediate: true
	}
);
watch(
	tabsMenuList,
	() => {
		if (authStore.selectedSysId !== 1) {
			tabsMenuValue.value = tabsMenuList.value[tabsMenuList.value.length - 1].path;
		}
	},
	{
		deep: true
	}
);

// Tab Click
const tabClick = (tabItem: TabsPaneContext) => {
	const path = tabItem.props.name as string;
	console.log(path);
	router.push(path);
};

// refresh page
const reload: Function = inject('refresh') as Function;

// Remove Tab
const tabRemove = (activeTabPath: string) => {
	// 删除keepAlive路由
	const deleteRouterName = activeTabPath.split('/');
	authStore.deleteKeepAliveRouter(deleteRouterName?.[2]);
	tabStore.removeTabs(activeTabPath, activeTabPath == route.fullPath || route.fullPath.indexOf('Info') !== -1);
	// 关闭当前页面后,需要刷新页面, 不然再次进入页面不会重新加载
	reload();
};
</script>

<style scoped lang="scss">
@import './index.scss';
</style>
